package org.abettor.nookinfo.novel;

import java.util.List;
import java.util.Random;

import org.abettor.nookinfo.R;
import org.abettor.nookinfo.ads.YoumiManager;
import org.abettor.nookinfo.persist.NovelHelper;
import org.abettor.nookinfo.persist.NovelHelper.LocalChapter;
import org.abettor.nookinfo.view.OnPageJumpListener;
import org.abettor.nookinfo.view.PageDialog;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.LinearLayout.LayoutParams;

/**
 * 本地文章列表
 * @author shawn
 *
 */
public class NovelLocalChapter extends Activity
{
	public static final String EXTRA_NOVEL_ID = "EXTRA_NOVEL_ID";
	public static final String EXTRA_NOVEL_NAME = "EXTRA_NOVEL_NAME";
	public static final String EXTRA_CHAPTER_ID = "EXTRA_CHAPTER_ID";
	private static final int REFRESHED = 1024;//文章更新事件
	private static final int PAGE_SIZE = 10;
	private static final int MENU_PREV = Menu.FIRST + 1;
	private static final int MENU_NEXT = MENU_PREV + 1;
	private static final int MENU_JUMP = MENU_NEXT + 1;
	private static final int MENU_REFRESH = MENU_JUMP + 1;
	private static final int MENU_DELETE = MENU_REFRESH + 1;
	private static final int MENU_CLOSE = MENU_DELETE + 1;
	private YoumiManager youmi = new YoumiManager(this);
	private NovelHelper novelHelper = new NovelHelper(this);
	private int novel;
	private String novelName;
	private int page = 1;
	private int total = -1;
	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			if(msg.what == REFRESHED)
			{
				total = novelHelper.getLocalChapterPageCount(novel, PAGE_SIZE);
				if(total > 0)
				{
					if(page > total)
					{
						page = total;
					}
					List<LocalChapter> chapterList = novelHelper.getLocalChapterList(novel, PAGE_SIZE, page);
					if(chapterList == null)
					{
						Builder builder = new Builder(NovelLocalChapter.this);
						builder.setTitle(R.string.novel_local_chapter_fail_title);
						builder.setMessage(R.string.novel_local_chapter_fail_content);
						builder.setPositiveButton(R.string.novel_local_chapter_fail_btn_ok, new DialogInterface.OnClickListener()
						{
							@Override
							public void onClick(DialogInterface dialoginterface, int i)
							{
								dialoginterface.dismiss();
							}
						});
						builder.show();
					}
					else
					{
						LinearLayout layout = (LinearLayout) findViewById(R.id.novelListLayout);
						layout.removeAllViews();
						LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
						for(LocalChapter chapter : chapterList)
						{
							//	显示文章列表
							final LocalChapter chap = chapter;
							Button btn = new Button(NovelLocalChapter.this);
							btn.setLayoutParams(params);
							btn.setBackgroundResource(R.drawable.novel_chapter_button);
							btn.setText(chap.name);
							btn.setOnClickListener(new OnClickListener()
							{
								@Override
								public void onClick(View view)
								{
									//	打开相应的文章内容
									Intent novelIntent = new Intent();
									novelIntent.setClass(NovelLocalChapter.this, NovelLocalContent.class);
									novelIntent.putExtra(EXTRA_NOVEL_NAME, novelName);
									novelIntent.putExtra(EXTRA_CHAPTER_ID, chap.id);
									startActivity(novelIntent);
								}
							});
							layout.addView(btn);
						}

						ScrollView scroll = (ScrollView) findViewById(R.id.novelListScroll);
						scroll.scrollTo(0, 0);

						//	按照一定的概率显示广告
						Random rand = new Random(System.currentTimeMillis());
						int val = rand.nextInt(99);
						if(val < 30)
						{
							youmi.showYoumi(YoumiManager.Position.top, Color.WHITE, Color.BLACK, 0xAA);
						}
					}
				}
				else
				{
					page = 0;
				}
			}

			super.handleMessage(msg);
		}
	};
	private Runnable worker = new Runnable()
	{
		@Override
		public void run()
		{
			Message msg = new Message();
			msg.what = REFRESHED;
			handler.sendMessage(msg);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.novel_local_chapter);
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		novelName = extras.getString(EXTRA_NOVEL_NAME);
		novel = extras.getInt(EXTRA_NOVEL_ID);
		String label = getString(R.string.novel_local_chapter_label).replace("REPL", novelName);
		setTitle(label);

		onRefreshClicked(null);
	}

	/**
	 * 创建Menu菜单
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_PREV, MENU_PREV, getString(R.string.global_menu_prev)).setIcon(R.drawable.global_menu_prev);
		menu.add(0, MENU_NEXT, MENU_NEXT, getString(R.string.global_menu_next)).setIcon(R.drawable.global_menu_next);
		menu.add(0, MENU_JUMP, MENU_JUMP, getString(R.string.global_menu_jump)).setIcon(R.drawable.global_menu_jump);
		menu.add(0, MENU_REFRESH, MENU_REFRESH, getString(R.string.global_menu_refresh)).setIcon(R.drawable.global_menu_refresh);
		menu.add(0, MENU_DELETE, MENU_DELETE, getString(R.string.global_menu_delete)).setIcon(R.drawable.global_menu_delete);
		menu.add(0, MENU_CLOSE, MENU_CLOSE, getString(R.string.global_menu_close)).setIcon(R.drawable.global_menu_close);

		return result;
	}

	/**
	 * 处理菜单事件
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch(item.getItemId())
		{
		case MENU_PREV:
			onPrevClicked(null);
			break;
		case MENU_NEXT:
			onNextClicked(null);
			break;
		case MENU_JUMP:
			//	跳转到……
			PageDialog pageDialog = new PageDialog(this, total, page);
			pageDialog.setTitle(R.string.global_menu_jump);
			pageDialog.setOnPageJumpListener(new OnPageJumpListener()
			{
				@Override
				public void onPageJump(PageDialog dialog)
				{
					int current = dialog.getCurrentPage();
					if(current <= 0 || current > total)
					{
						return;
					}

					page = current;
					dialog.dismiss();
					onRefreshClicked(null);
				}
			});
			pageDialog.show();
			break;
		case MENU_REFRESH:
			onRefreshClicked(null);
			break;
		case MENU_DELETE:
			//	删除本地文章
			Builder builder = new Builder(this);
			builder.setTitle(R.string.novel_local_chapter_delete_title);
			builder.setMessage(R.string.novel_local_chapter_delete_content);
			builder.setPositiveButton(R.string.novel_local_chapter_delete_btn_ok, new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					dialog.dismiss();
					novelHelper.removeLocalNovel(novel);
					onRetrunClicked(null);
				}
			});
			builder.setNegativeButton(R.string.novel_local_chapter_delete_btn_cancel, new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					dialog.dismiss();
				}
			});
			builder.show();
			break;
		case MENU_CLOSE:
			onRetrunClicked(null);
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	/**
	 * “刷新”按钮事件方法
	 * @param v
	 */
	public void onRefreshClicked(View v)
	{
		handler.postDelayed(worker, 100);
	}

	/**
	 * “返回”按钮事件方法
	 * @param v
	 */
	public void onRetrunClicked(View v)
	{
		finish();
	}

	/**
	 * “上一页”按钮事件方法
	 * @param v
	 */
	public void onPrevClicked(View v)
	{
		if(page <= 1)
		{
			return;
		}

		page --;
		onRefreshClicked(v);
	}

	/**
	 * “下一页”按钮事件方法
	 * @param v
	 */
	public void onNextClicked(View v)
	{
		page ++;
		onRefreshClicked(v);
	}
}
